package com.kongjs.application.service.impl;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import com.kongjs.application.config.CaptchaProperties;
import com.kongjs.application.enums.CaptchaType;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class CaptchaService {

    @Resource
    private CaptchaProperties captchaProperties;

    public AbstractCaptcha getCaptcha() {
        CaptchaType captchaType = captchaProperties.getType();
        if (captchaType.equals(CaptchaType.Random)) {
            CaptchaType[] values = CaptchaType.values();
            final Random random = new Random();
            int i = random.nextInt(4);
            CaptchaType type = values[i];
            return getCaptcha(type);
        }
        return getCaptcha(captchaType);
    }

    public AbstractCaptcha getCaptcha(CaptchaType captchaType) {
        Integer width = captchaProperties.getWidth();
        Integer height = captchaProperties.getHeight();
        Integer codeCount = captchaProperties.getCodeCount();
        Integer lineCount = captchaProperties.getLineCount();
        Integer circleCount = captchaProperties.getCircleCount();
        Integer thickness = captchaProperties.getThickness();
        Float size = captchaProperties.getSize();
        AbstractCaptcha captcha = null;
        if (captchaType.equals(CaptchaType.LineCaptcha)) {
            captcha = CaptchaUtil.createLineCaptcha(width, height, codeCount, lineCount, size);
        }
        if (captchaType.equals(CaptchaType.CircleCaptcha)) {
            captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, circleCount, size);
        }
        if (captchaType.equals(CaptchaType.ShearCaptcha)) {
            captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, thickness, size);
        }
        if (captchaType.equals(CaptchaType.GifCaptcha)) {
            captcha = CaptchaUtil.createGifCaptcha(width, height, codeCount, thickness, size);
        }
        return captcha;
    }
}
